from fastapi import APIRouter, UploadFile, File, HTTPException
from core.pdf_utils import pdf_to_images, cleanup_temp_files
from core.image_utils import image_to_opencv, find_image_diff
from core.config import settings
import os

router = APIRouter()


@router.post("/compare")
async def compare_pdfs(file1: UploadFile = File(...), file2: UploadFile = File(...)):
    # 验证文件类型
    if not (file1.filename.endswith(".pdf") and file2.filename.endswith(".pdf")):
        raise HTTPException(400, "仅支持PDF文件")

    # 创建临时目录
    os.makedirs(settings.temp_dir, exist_ok=True)

    # 保存临时文件
    file1_path = os.path.join(settings.temp_dir, file1.filename)
    file2_path = os.path.join(settings.temp_dir, file2.filename)

    with open(file1_path, "wb") as f:
        f.write(await file1.read())
    with open(file2_path, "wb") as f:
        f.write(await file2.read())

    try:
        # 转换为图片
        images1 = pdf_to_images(file1_path)
        images2 = pdf_to_images(file2_path)

        # 检查页数
        if len(images1) != len(images2):
            raise HTTPException(400, "PDF页数不一致")

        # 逐页比较
        diffs = []
        for page_num, (img1, img2) in enumerate(zip(images1, images2)):
            cv_img1 = image_to_opencv(img1)
            cv_img2 = image_to_opencv(img2)
            regions = find_image_diff(cv_img1, cv_img2)
            if regions:
                diffs.append({"page": page_num + 1, "regions": regions})

        return {"differences": diffs}

    except Exception as e:
        raise HTTPException(500, f"处理失败: {str(e)}")
    finally:
        cleanup_temp_files(file1_path, file2_path)
